<!-- 
    time：20024-4-15
    name：meidusa 
    role：图片压缩
 -->
 
<template>
    <div class="img-compress-box">
        <input type="file" id="file" ref="file" @change="GetImgInfo">
    </div>
</template>

<script setup lang='ts'>
import { ref } from 'vue';

const props = defineProps({
    quality: {
        type: Number,
        defaule: 1
    }
})
const emit = defineEmits(['updateCompressImg'])

const file = ref('')    // input实例

/**
 * 读取图片信息
 * @param e 
 */
const GetImgInfo = (e: any) => {
    const target = e.target
    const fileObj = target.files?.[0]   // 读到file对象
    if (fileObj) {
        CompressImg(fileObj, props.quality)
    }
}

/**
 * 压缩图片
 */
const CompressImg = (fileval: any, qualityval: any) => {
    const fileReader = new FileReader() // 创建图片读取器

    fileReader.onload = (e) => {    // 异步读取
        const url = e.target?.result    // 得到base64
        const img = new Image()
        const canvas = document.createElement('canvas') // 这样创建是因为一开始页面就不会显示canvas的宽高，就不会占据页面的空间
        const ctx = canvas.getContext('2d')

        img.src = url as string
        img.onload = () => {
            canvas.width = img.width
            canvas.height = img.height
            ctx?.drawImage(img, 0, 0, img.width, img.height)    // 将图画到canvas
            const base64 = canvas.toDataURL('image/jpeg', qualityval) // 转base64
            document.body.innerHTML = `<img src="${base64}">`
            emit('updateCompressImg', base64)
        }
    }
    fileReader.readAsDataURL(fileval)  // 读取
}



</script>
<style lang="scss" scoped></style>